package oop封装;

import java.io.*;
import java.net.Socket;

/**
 * oop封装：在线聊天室的发送端
 */
public class Send implements Runnable{
    private Socket client;
    private BufferedReader br;
    private DataOutputStream dos;
    private boolean isRunning;
    private String name;
    public Send(Socket client,String name){
        this.name = name;
        this.client = client;
        br = new BufferedReader(new InputStreamReader(System.in));
        isRunning = true;

        try {
            dos = new DataOutputStream(client.getOutputStream());
            send(this.name);
        } catch (IOException e) {
            closeAll(client,br,dos);
        }
    }
    //发送消息
    public void send(String mag){
        try {
            if (!mag.equals("")){
                dos.writeUTF(mag);
                dos.flush();
            }else {
                closeAll(client,br,dos);
            }
        } catch (IOException e) {
            closeAll(client,br,dos);
        }
    }
    public String getFormasege(){
        try {
            String mag = br.readLine();
            return  mag;
        } catch (IOException e) {
            closeAll(client,br,dos);
        }
        return "";
    }
    @Override
    public void run() {
        while (isRunning){
            String mag = getFormasege();
            if (!mag.equals("")){
                send(mag);
            }else {
                closeAll(client,br,dos);
            }
        }
    }
    public void closeAll(Closeable...closeables){
        for (Closeable close: closeables) {
            try {
                if (null != close) {
                    close.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        isRunning = false;
    }
}
